package exception

import (
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"go-web-demo/config/jwt/exception"
	"net/http"
	"runtime/debug"
)

// ErrHandle 统一异常处理
func ErrHandle(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			apiErr, isApiErr := r.(*ApiError)
			jwtErr, isJwtErr := r.(*exception.JwtError)
			if isApiErr {
				// 打印错误堆栈信息
				log.WithField("ErrMsg", apiErr.Error()).Error("PanicHandler handled apiError: ")
				// 封装通用json返回
				c.JSON(http.StatusInternalServerError, apiErr)
			} else if isJwtErr {
				// 打印错误堆栈信息
				log.WithField("ErrMsg", jwtErr.Error()).Error("PanicHandler handled apiError: ")
				// 封装通用json返回
				c.JSON(http.StatusUnauthorized, jwtErr)
			} else {
				// 打印错误堆栈信息
				err := r.(error)
				log.WithField("ErrMsg", err.Error()).Error("PanicHandler handled ordinaryError: ")
				debug.PrintStack()
				// 封装通用json返回
				c.JSON(http.StatusInternalServerError, NewApiError(InternalServerError, GetResultMsg(InternalServerError)))
			}
			c.Abort()
		}
	}()
	c.Next()
}
